<template>
  <div class="race">
    <div class="r-header">
      <div class="r-h-title"> <i class="iconfont icon-liebiao1"></i>比赛题目列表</div>
    </div>
    <div class="r-search">
      <n-input class="r-s-input" placeholder="搜索比赛题目" round size="small" v-model:value="searchVal">
        <template #suffix>
          <i class="iconfont icon-sousuo" @click="searchParams.name = searchVal"></i>
        </template>
      </n-input>
      <n-button class="r-s-btn" size="small" round type="success" @click="isShowAppend = true">
        <i class="iconfont icon-tianjia"></i>添加题目</n-button>
    </div>
    <div class="t-table">
      <el-table :data="problem.records" size="small" stripe>
        <el-table-column type="index" label="序号" width="100%" align="center" :index="indexMethod2" />
        <el-table-column prop="pid" label="题目ID" align="center"></el-table-column>
        <el-table-column prop="problem.title" label="题目" align="center"></el-table-column>
        <el-table-column prop="" label="赛内信息" align="center">
          <template #default="scoped">
            <div class="box">
              <div>展示ID:{{ scoped.row.displayId }}</div>
              <div>标题：{{ scoped.row.displayTitle }}</div>
              <div>颜色：<el-color-picker v-model="scoped.row.color" disabled /></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="problem.author" label="作者" align="center"></el-table-column>
        <el-table-column label="所属阶段" align="center" v-if="route.params.type == 3">
          <template #default="scoped">
            <el-select size="small" placeholder="请选择阶段" v-model="scoped.row.stage"
              @change="editProblem = scoped.row, updateRace(editProblem)">
              <el-option v-for="(item, index) in (raceData.tiantiStageConfig.stage.length + 1)" :key="index"
                :label="'第' + (index + 1) + '阶段'" :value="index + 1"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template #default="scoped">
            <div class="t-t-comparation">
              <el-tooltip content="编辑" placement="top">
                <n-button class="nbtn" size="tiny" type="info" @click="editRaceProblem(scoped.row)"><i
                    class="iconfont icon-bianji"></i></n-button>
              </el-tooltip>
              <el-tooltip content="移出比赛" placement="top">
                <n-button class="nbtn" size="tiny" type="warning" @click="delRaceProblem(scoped.row.id)"><i
                    class="iconfont icon-shanchu"></i></n-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>

      </el-table>
    </div>
    <div class="t-footer">
      <el-pagination class="pagination" :page-sizes="[20, 50, 100]" background small layout="prev, pager, next,sizes"
        :total="Number(problem.total)" v-model:current-page="searchParams.pageNum"
        v-model:page-size="searchParams.pageSize" />
    </div>
    <n-modal v-model:show="isShowAppend">
      <n-card :bordered="false" role="dialog" aria-modal="true" class="card">
        <div class="container">
          <h2 class="bigtitle">题目列表</h2>
          <div class="c-search">
            <n-input class="c-s-input" placeholder="搜索题目" round size="small" v-model:value="proSearchVal">
              <template #suffix>
                <i class="iconfont icon-sousuo" @click="searchParams2.name = proSearchVal"></i>
              </template>
            </n-input>
            <n-select class="select" size="small" v-model:value="searchParams2.isPublic"
              :options="isPublics"></n-select>
          </div>
          <el-table :data="unUsedProblem.records" stripe class="problemTable">
            <el-table-column type="index" label="序号" width="100%" align="center" :index="indexMethod" />
            <el-table-column prop="problemId" label="题目ID" />
            <el-table-column prop="title" label="题目">
              <template #default="scoped">
                <div class="problemTable-title">{{ scoped.row.title }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="difficulty" label="难度" align="center">
              <template #default="scoped">
                <el-tag round size="small" type="success" v-show="scoped.row.difficulty === 0">简单</el-tag>
                <el-tag round size="small" type="warning" v-show="scoped.row.difficulty === 1">中等</el-tag>
                <el-tag round size="small" type="danger" v-show="scoped.row.difficulty === 2">困难</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="ioScore" label="操作" align="center">
              <template #default="scoped">
                <div>
                  <n-button size="small" type="success" @click="updateCurrentProblem(scoped.row)"><i
                      class="iconfont icon-tianjia "></i></n-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="c-footer">
            <el-pagination class="pagination" :page-sizes="[20, 50, 100]" background small
              layout="prev, pager, next,sizes" :total="Number(unUsedProblem.total)"
              v-model:current-page="searchParams2.pageNum" v-model:page-size="searchParams2.pageSize" />
          </div>
        </div>
        <el-dialog v-model="isShowAppendDialog" title="题目参数" width="500">
          <div class="teaminput">
            <div class="box">
              展示ID：<n-input size="small" class="input" placeholder=""
                v-model:value="currentProblem.displayId"></n-input>
            </div>
            <div class="box">
              展示标题：<n-input size="small" class="input" placeholder=""
                v-model:value="currentProblem.displayTitle"></n-input>
            </div>
            <div class="box" v-if="route.params.type == 3">
              阶段：<el-select class="input" size="small" placeholder="请选择阶段" v-model="currentProblem.stage">
                <el-option v-for="(item, index) in (raceData.tiantiStageConfig.stage.length + 1)" :key="index"
                  :label="'第' + (index + 1) + '阶段'" :value="index + 1"></el-option>
              </el-select>
            </div>
            <div class="box">
              颜色：<div class="colorPicker"><el-color-picker v-model="currentProblem.color" /></div>
            </div>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <n-button class="btn" round @click="isShowAppendDialog = false">取消</n-button>
              <n-button class="btn" round type="success" @click="appendToRace()">
                确定
              </n-button>
            </div>
          </template>
        </el-dialog>
      </n-card>
    </n-modal>
    <el-dialog v-model="isShowEditDialog" title="题目参数" width="500">
      <div class="teaminput">
        <div class="box">
          展示ID：<n-input size="small" class="input" placeholder="" v-model:value="editProblem.displayId"></n-input>
        </div>
        <div class="box">
          展示标题：<n-input size="small" class="input" placeholder="" v-model:value="editProblem.displayTitle"></n-input>
        </div>
        <div class="box">
          颜色：<div class="colorPicker"><el-color-picker v-model="editProblem.color" /></div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <n-button class="btn" round @click="isShowEditDialog = false">取消</n-button>
          <n-button class="btn" round type="success" @click="updateRace(editProblem)">
            确定
          </n-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, reactive, onMounted } from "vue"
import { debounce } from "@/utils/global.js"
import { ElMessage } from 'element-plus'
import { getRaceProblemsAPI, getRaceDetailAPI, getUnUsedProblemsAPI, appendProblemToRaceAPI, delRaceProblemAPI, updateRaceProblemAPI } from "@/api/adminAPI/adminAPI"
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()


const searchParams = reactive({
  pageSize: 20,
  pageNum: 1,
  cid: '',
  name: ''
})
watch(searchParams, () => {
  getRaceProblems()
})
const problem = ref({
  records: [],
  total: 10
})
const getRaceProblems = debounce(async () => {
  await getRaceProblemsAPI(searchParams).then(res => {
    if (res.data.code === 200) {
      if (res.data.data) {
        problem.value = res.data.data
      }
    }
  }).catch(err => {
    console.log(err)
  })
}, 300)

onMounted(() => {
  searchParams.cid = route.params.cid
  searchParams2.cid = route.params.cid
  searchParams2.type = route.params.type == 0 ? 0 : 1
  currentProblem.cid = route.params.cid
})
const indexMethod = (index) => {
  return (searchParams2.pageNum - 1) * searchParams2.pageSize + index + 1
}
const indexMethod2 = (index) => {
  return (searchParams.pageNum - 1) * searchParams.pageSize + index + 1
}
const searchVal = ref('')
const isShowAppend = ref(false)


const searchParams2 = reactive({
  pageSize: 20,
  pageNum: 1,
  cid: '',
  name: '',
  type: 0,
  isPublic: 1
})
watch(searchParams2, () => {
  getUnUsedProblems()
  if (route.params.type == 3) {
    getRaceDetail(route.params.cid)
  }
})
const unUsedProblem = ref({
  records: [],
  total: 20
})
const getUnUsedProblems = debounce(async () => {
  await getUnUsedProblemsAPI(searchParams2).then(res => {
    if (res.data.code === 200) {
      if (res.data.data)
        unUsedProblem.value = res.data.data
    }
  }).catch(err => {
    console.log(err)
  })
}, 200)

const proSearchVal = ref('')
const currentProblem = reactive({
  cid: '',
  pid: '',
  color: '',
  displayId: '',
  displayTitle: '',
  stage: null
})
const appendToRace = debounce(async () => {
  if (currentProblem.displayId.length == 0) {
    ElMessage.error("请输入题目展示ID")
    return
  }
  if (currentProblem.displayTitle.length == 0) {
    ElMessage.error("请输入题目展示标题")
    return
  }
  if (currentProblem.color.length == 0) {
    ElMessage.error("请选择题目展示颜色")
    return
  }
  if (route.params.type == 3 && !(currentProblem.stage > 0)) {
    ElMessage.error("请选择题目所属阶段")
    return
  }
  await appendProblemToRaceAPI(currentProblem).then(res => {
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg)
      isShowAppendDialog.value = false
      getUnUsedProblems()
      getRaceProblems()
      Object.assign(currentProblem, {
        cid: route.params.cid,
        pid: '',
        color: '',
        displayId: '',
        displayTitle: '',
        stage: null,
      })
    }
  }).catch(err => {
    console.log(err)
  })
}, 200)
const updateCurrentProblem = (row) => {
  isShowAppendDialog.value = true
  currentProblem.pid = row.id
  currentProblem.displayTitle = row.title
}
const isShowAppendDialog = ref(false)


const delRaceProblem = debounce(async (id) => {
  await delRaceProblemAPI([id]).then(res => {
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg)
      getUnUsedProblems()
      getRaceProblems()
    }
  }).catch(err => {
    console.log(err)
  })
}, 200)

const isPublics = [
  {
    label: '私有题库',
    value: 0
  },
  {
    label: '公共/比赛题库',
    value: 1
  }
]
const editProblem = reactive({
  cpid: '',
  color: '',
  displayId: '',
  displayTitle: '',
  stage: null
})
const isShowEditDialog = ref(false)
const editRaceProblem = (row) => {
  Object.assign(editProblem, row)
  editProblem.cpid = row.id
  isShowEditDialog.value = true
}

const updateRace = async (data) => {
  if (data.displayId.length == 0) {
    ElMessage.error("请输入题目展示ID")
    return
  }
  if (data.displayTitle.length == 0) {
    ElMessage.error("请输入题目展示标题")
    return
  }
  if (data.color.length == 0) {
    ElMessage.error("请选择题目展示颜色")
    return
  }
  if (route.params.type == 3 && !(data.stage > 0)) {
    ElMessage.error("请选择题目所属阶段")
    return
  }
  await updateRaceProblemAPI(data).then(res => {
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg)
      isShowEditDialog.value = false
      getUnUsedProblems()
      getRaceProblems()
    }
  }).catch(err => {
    console.log(err)
  })
}

const raceData = ref({})
const getRaceDetail = debounce(async (cid) => {
  await getRaceDetailAPI(cid)
    .then((res) => {
      if (res.data.code === 200) {
        if (res.data.data.format == 3 && res.data.data.tiantiStageConfig.length > 0) {
          res.data.data.tiantiStageConfig = JSON.parse(res.data.data.tiantiStageConfig)
          const arr1 = res.data.data.tiantiStageConfig.stage.map(v => {
            return { score: v }
          })
          let flag = 1
          const arr2 = []
          for (let i = 0; i < res.data.data.tiantiStageConfig.personalScore.length; i++) {
            const ele = res.data.data.tiantiStageConfig.personalScore[i]
            const ele1 = res.data.data.tiantiStageConfig.personalScore[i + 1]
            if (ele != ele1) {
              arr2.push({
                num: flag,
                score: ele
              })
              flag = 1
            } else {
              flag += 1
            }
          }
          res.data.data.tiantiStageConfig.stage = arr1
          res.data.data.tiantiStageConfig.personalScore = arr2
        }
        raceData.value = res.data.data
      }
    })
    .catch((err) => {
      console.log(err)
    })
}, 100)
</script>

<style lang="less" scoped>
.race {
  margin: auto;
  width: 96%;
  height: 92vh;
  padding: 10px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 12px 12px 50px #d9d9d9,
    -12px -12px 50px #ffffff;
  display: flex;
  flex-direction: column;

  .r-header {
    display: flex;

    .r-h-title {
      height: 30px;
      line-height: 30px;
      font-size: 20px;
      font-weight: 600;
      color: #555;
      display: flex;
      text-align: center;

      .iconfont {
        margin: auto 0;
        font-weight: 700;
        font-size: 28px;
        height: 30px;
      }
    }
  }


  .r-search {
    display: flex;
    height: 30px;
    line-height: 30px;
    margin: 20px 0 0 0;
    padding-bottom: 10px;
    border-bottom: 2px solid @lineColor;

    .r-s-input {
      height: 30px;
      line-height: 30px;
      width: 20%;
    }

    .r-s-btn {
      margin: auto 20px;
    }
  }

  .t-table {
    width: 100%;
    margin: 10px auto 0 auto;
    height: 72vh;

    .t-t-input {
      display: flex;
      justify-content: center;

      .inputNumber {
        width: 100px;
      }

    }


    .t-t-comparation {
      display: flex;
      justify-content: center;

      .nbtn {
        margin: auto 2px;
      }
    }
  }

  .t-footer {
    margin: auto auto 0 auto;
    display: flex;
    justify-content: center;
  }
}

.card {
  width: 80vw;
  height: 85vh;
  border-radius: 20px;
  overflow: hidden;

  .container {
    display: flex;
    flex-direction: column;
    height: 82vh;

    .bigtitle {
      border-bottom: 1px solid @bgColor;
      padding-bottom: 10px;
    }

    .c-search {
      display: flex;
      height: 30px;
      line-height: 30px;
      margin: 20px 0 0 0;
      padding-bottom: 10px;
      border-bottom: 2px solid @lineColor;

      .c-s-input {
        height: 30px;
        line-height: 30px;
        width: 20%;
      }

      .select {
        width: 15%;
        margin: auto 30px;
      }

      .c-s-btn {
        width: 80px;
        margin: auto 20px;
      }
    }

    .problemTable {
      height: 75%;
    }

    .c-footer {
      margin: auto auto 0 auto;
      padding-top: 5px;
      display: flex;
      justify-content: center;
    }
  }


}

::v-deep(.n-card__content) {
  padding: 10px !important;
}

.teaminput {
  display: flex;
  flex-direction: column;

  .box {
    margin: 0 auto;
    display: flex;
    height: 30px;
    line-height: 30px;
    width: 80%;

    .input {
      width: 80%;
      margin: 2px 0 0 auto;
    }

    .colorPicker {
      margin: 2px auto;
    }

    .btn {
      margin: auto;
    }
  }
}

.box {
  font-weight: 550;
  font-size: 12px;
  color: black;
}
</style>